import type { Doc } from '@/modules/doc/types/doc.ts'

/**
 * 文档数据处理工具函数
 */

/**
 * 将文档树结构展平为一维数组
 * @param documents 文档树数组
 * @returns 展平后的文档数组
 */
export const flattenDocumentTree = (documents: any[]): Doc[] => {
  const result: Doc[] = []
  
  const flatten = (docs: any[], parentId: string | null = null) => {
    docs.forEach(doc => {
      const document: Doc = {
        id: doc.id,
        name: doc.name,
        content: doc.content || '',
        parentId: parentId,
        namespaceId: doc.namespaceId,
        permission: doc.permission,
        sortNo: doc.sortNo || 0,
        children: [],
        items: doc.items || [],
        createdTime: doc.createdTime,
        updatedTime: doc.updatedTime,
        layoutType: doc.layoutType,
        isFavorite: doc.isFavorite
      }
      
      result.push(document)
      
      if (doc.children && doc.children.length > 0) {
        flatten(doc.children, doc.id)
      }
    })
  }
  
  flatten(documents)
  return result
}

/**
 * 构建文档树结构
 * @param documents 文档平面数组
 * @returns 树形结构的文档数组
 */
export const buildDocumentTree = (documents: Doc[]): Doc[] => {
  const documentMap = new Map<string, Doc>()
  const roots: Doc[] = []

  // 创建映射
  documents.forEach(doc => {
    documentMap.set(doc.id, { ...doc, children: [] })
  })

  // 构建树结构
  documents.forEach(doc => {
    const documentNode = documentMap.get(doc.id)!
    
    if (doc.parentId && documentMap.has(doc.parentId)) {
      const parent = documentMap.get(doc.parentId)!
      if (!parent.children) parent.children = []
      parent.children.push(documentNode)
    } else {
      roots.push(documentNode)
    }
  })

  return roots
}

/**
 * 根据关键词过滤文档
 * @param documents 文档数组
 * @param keyword 搜索关键词
 * @returns 过滤后的文档数组
 */
export const filterDocumentsByKeyword = (documents: Doc[], keyword: string): Doc[] => {
  if (!keyword.trim()) return documents
  
  const lowerKeyword = keyword.toLowerCase()
  
  return documents.filter(doc => 
    doc.name.toLowerCase().includes(lowerKeyword) ||
    doc.content.toLowerCase().includes(lowerKeyword)
  )
}

/**
 * 按排序号和创建时间排序文档
 * @param documents 文档数组
 * @returns 排序后的文档数组
 */
export const sortDocuments = (documents: Doc[]): Doc[] => {
  return [...documents].sort((a, b) => {
    // 先按 sortNo 排序
    const aSortNo = a.sortNo ?? 0
    const bSortNo = b.sortNo ?? 0
    if (aSortNo !== bSortNo) {
      return aSortNo - bSortNo
    }
    
    // sortNo 相同时按创建时间排序
    const aTime = new Date(a.createdTime || 0).getTime()
    const bTime = new Date(b.createdTime || 0).getTime()
    return aTime - bTime
  })
}

/**
 * 查找文档的所有父级文档
 * @param documentId 文档ID
 * @param documents 所有文档数组
 * @returns 父级文档路径数组
 */
export const getDocumentParents = (documentId: string, documents: Doc[]): Doc[] => {
  const parents: Doc[] = []
  const documentMap = new Map<string, Doc>()
  
  documents.forEach(doc => documentMap.set(doc.id, doc))
  
  let currentDoc = documentMap.get(documentId)
  
  while (currentDoc?.parentId) {
    const parent = documentMap.get(currentDoc.parentId)
    if (parent) {
      parents.unshift(parent) // 添加到开头，保持正确顺序
      currentDoc = parent
    } else {
      break
    }
  }
  
  return parents
}